package com.example.cinema.drawview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class RoundImage extends androidx.appcompat.widget.AppCompatImageView {
    public RoundImage(@NonNull Context context) {
        this(context,null);
    }

    public RoundImage(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public RoundImage(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    Paint paint;
    Paint paint1;
    Matrix matrix;
    private void  init()
    {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.GREEN);
        matrix = new Matrix();
//        setLayerType(View.LAYER_TYPE_SOFTWARE,null);

        paint1 = new Paint();
        paint1.setAntiAlias(true);
        paint1.setDither(true);
        paint1.setColor(Color.GREEN);
    }

    @Override
    protected void onDraw(Canvas canvas) {



        Drawable dra = getDrawable();
        if(dra instanceof BitmapDrawable)
        {
            BitmapDrawable btm = (BitmapDrawable) dra;
            Bitmap bitmap = btm.getBitmap();
            Round(bitmap,canvas);
        }else {
            super.onDraw(canvas);
        }
    }

    private int btmwidth;
    private int btmheigh;
    private int width;
    private int heigh;
    private void Round(Bitmap bitmap,Canvas canvas)
    {
        btmwidth = bitmap.getWidth();
        btmheigh = bitmap.getHeight();
        width = getWidth();
        heigh = getHeight();
        BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
        matrix.reset();
        float  scale = Math.min((float) width/btmwidth,(float) heigh/btmheigh);

        matrix.setScale(scale,scale);
        shader.setLocalMatrix(matrix);
        paint.setShader(shader);

        canvas.drawCircle(width/2,width/2,width/2,paint1);
        canvas.drawCircle(width/2,heigh/2,width/2,paint);
    }

}
